Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Python Class → self in Python class

Python Class

self in Python class

`self` in Python Classes

Object-Oriented Programming (OOP) revolves around the concept of objects, which encapsulate data (attributes) and actions (methods). In Python, classes serve as blueprints for creating these objects. The special keyword `self` plays a crucial role in connecting an object's attributes and methods. Let's unravel its significance through detailed explanations and examples.

What is `self`?

`self` is a convention (not a keyword in the strictest sense, but a crucial parameter). It's the first parameter in every method definition within a class. It refers to *the instance* of the class. Think of it as a handle or reference to the specific object being worked upon. When you call a method on an object (e.g., `my_object.my_method()`), Python automatically passes the object itself as the first argument to the method, assigning it to the `self` parameter.

Why use `self`?

Without `self`, the method wouldn't have access to the object's attributes. Each object of a class has its own unique set of attributes. `self` ensures that methods operate on the correct object's data. It acts as a bridge between the object's internal state and its methods. Example 1: Basic `self` Usage
Basic "self" example in python class Dog: def __init__(self, name, breed): # Constructor (__init__ method) self.name = name # Assign name to the object's attribute self.breed = breed # Assign breed to the object's attribute def bark(self): # Method to make the dog bark print(f"{self.name} says Woof!") def describe(self): print(f"My name is {self.name}, and I'm a {self.breed}.") my_dog = Dog("Buddy", "Golden Retriever") my_dog.bark() my_dog.describe() another_dog = Dog("Lucy", "Labrador") another_dog.bark()

Output

Buddy says Woof! My name is Buddy, and I'm a Golden Retriever. Lucy says Woof!

Explanation ⮞ __init__` (the constructor) uses `self` to initialize the object's attributes (`name` and `breed`). Each `Dog` object gets its own `name` and `breed`. ⮞ bark` and `describe` methods use `self` to access the object's `name` and `breed` attributes. Note that `self.name` refers to the `name` attribute of the specific `Dog` object the method is called upon. Example 2: Modifying Attributes using `self`
Modifying Attributes using `self` in python class Car: def __init__(self, make, model, speed=0): self.make = make self.model = model self.speed = speed def accelerate(self, increment): self.speed += increment print(f"{self.make} {self.model} is now going at {self.speed} mph.") my_car = Car("Toyota", "Camry") my_car.accelerate(20) my_car.accelerate(10)

Output

Toyota Camry is now going at 20 mph. Toyota Camry is now going at 30 mph.
Here, `accelerate` modifies the `speed` attribute of the specific `Car` object using `self.speed`.
Example 3: `self` in Class Methods vs. Static Methods Python offers class methods (@classmethod) and static methods (@staticmethod) in addition to instance methods. `self` is *not* used in class methods or static methods.
Python `self` in Class Methods vs. Static Methods class Circle: pi = 3.14159 def __init__(self, radius): self.radius = radius def area(self): # Instance method return self.pi * self.radius**2 @classmethod def from_diameter(cls, diameter): # Class method radius = diameter / 2 return cls(radius) # cls refers to the Circle class @staticmethod def is_valid_radius(radius): # Static method return radius > 0 c1 = Circle(5) print(c1.area()) c2 = Circle.from_diameter(10) # Using class method to create a circle print(c2.area()) print(Circle.is_valid_radius(5)) print(Circle.is_valid_radius(-2))

Output

78.53975 78.53975 True False
Class methods operate on the class itself (using `cls`), while static methods are just utility functions related to the class but don't directly use class state or the instance.
In summary: `self` is indispensable in Python classes. It's the mechanism that links methods to the specific object's attributes, allowing each object to maintain its own unique state and behavior. Understanding its role is fundamental to mastering OOP in Python. Remember that while `self` is a convention, consistently using it makes your code clearer and easier to maintain.

Tutorials